//创建WebGL上下文
const canvas = document.querySelector('canvas')
const gl = canvas.getContext('webgl');

//顶点着色器
const vertex = `
        attribute vec2 position;
        varying vec4 color;
        void main(){
          gl_PointSize =1.0;
          gl_Position = vec4(position , 1.0 , 1.0);
          color = vec4(0.5 *(vec2(1.0) + position), 0.0 , 1.0);
        }
`;

//片源着色器
const fragment = `
        precision mediump float;
        varying vec4 color;
        void main(){
            //gl_FragColor = vec4( 0.0 , 1.0 , 0.5 , 1.0);
            gl_FragColor = color; 
        }
`;

//绑定顶点着色器
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vertex);
gl.compileShader(vertexShader);

//绑定片源着色器
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fragment);
gl.compileShader(fragmentShader);

//创建program
const program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
gl.useProgram(program);


//定义顶点坐标
const points = new Float32Array([
    -1, -1,
    0, 1,
    1, -1
]);

//将数据存入缓冲区
const bufferId = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, bufferId);
gl.bufferData(gl.ARRAY_BUFFER, points, gl.STATIC_DRAW);

//将缓冲区数据读取到GPU
const vPosition = gl.getAttribLocation(program, 'position');
gl.vertexAttribPointer(vPosition, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(vPosition);

// 清除缓存区
gl.clear(gl.COLOR_BUFFER_BIT);
//绘制
gl.drawArrays(gl.TRIANGLES, 0, points.length / 2);





